package com.ebt.m.utils;

import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;

import com.ebt.m.commons.utils.Logger;

/**
 * Created by wanglu on 2017/3/21.
 */

public class KeyboardChangeListener implements ViewTreeObserver.OnGlobalLayoutListener {
    private static final String TAG = "ListenerHandler";
    private View mContentView;
    private int mToolbarHeight;
    private boolean isShow = false;
    private KeyBoardListener mKeyBoardListen;

    public interface KeyBoardListener {
        /**
         * call back
         *
         * @param isShow         true is show else hidden
         * @param keyboardHeight keyboard height
         */
        void onKeyboardChange(boolean isShow, int keyboardHeight);
    }

    public void setKeyBoardListener(KeyBoardListener keyBoardListen) {
        this.mKeyBoardListen = keyBoardListen;
    }

    public KeyboardChangeListener(View view, int toolbarHeight) {
        if (view == null) {
            return;
        }
        mToolbarHeight = toolbarHeight;
        mContentView = view;
        if (mContentView != null) {
            addContentTreeObserver();
        }
    }

    private void addContentTreeObserver() {
        mContentView.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @Override
    public void onGlobalLayout() {
        int currHeight = mContentView.getRootView().getHeight();
        Rect rect = new Rect();
        this.mContentView.getWindowVisibleDisplayFrame(rect);
        int height = (currHeight - mToolbarHeight) - (rect.bottom - rect.top);
        Logger.i("->currHeight = " + currHeight + "\n"
                + "rect.top = " + rect.top + "\n"
                + "rect.bottom = " + rect.bottom + "\n"
                + "height = " + height);
        if (!this.isShow && height > 200) {
            isShow = true;
        } else if (this.isShow && height < 200) {
            isShow = false;
        }
        if (mKeyBoardListen != null) {
            mKeyBoardListen.onKeyboardChange(isShow, height);
        }
    }

    public void destroy() {
        if (mContentView != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                mContentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        }
    }
}